package com.bree.erp.jsf.httpsess;

import java.io.Serializable;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.apache.log4j.Logger;

import com.bree.erp.entity.Returns;

@ManagedBean(name = "clipboardSession")
@SessionScoped
public class Clipboard implements Serializable {
	
	private static final long serialVersionUID = 1L;

	private static Logger LOG = Logger.getLogger(Clipboard.class);
	
	private List<Returns> reserveList = new ArrayList<Returns>();
	
	private Map<Long, Double> mapReserved = new AbstractMap<Long, Double>() {

		@Override
		public Set<java.util.Map.Entry<Long, Double>> entrySet() {
			return null;
		}
		
		@Override
		public Double get(Object key) {
			
			double sum = 0;

			if(key instanceof Long) {
				Long partUnitId = (Long) key;
				
				for(Returns returns : reserveList) {
					if(partUnitId.equals(returns.getPartUnit().getId())) {
						sum += returns.getQuantity();
					}
				}
			}
			
			return sum;

		}
		
	};
	
	public double getWareshouseReserved(String warehouseId, Long partUnitId) {

		double sum = 0.0;
		for(Returns returns : reserveList) {
			if(warehouseId.equals(returns.getWarehouse().getId()) && partUnitId.equals(returns.getPartUnit().getId())) {
				sum += returns.getQuantity();
			}
		}
		
		return sum;
	}


	public void reserve(Returns reserve) {
		
		Returns existing = search(reserve);
		if(existing != null) {
			double sum = existing.getQuantity() + reserve.getQuantity();
			existing.setQuantity(sum);
		} else {
			reserve.setId(new Date().getTime());
			reserveList.add(reserve);
		}
		int sz = reserveList.size();
		
		LOG.debug("new reserve list size: " + sz);
	}
	
	
	
	private Returns search(Returns reserve) {
		
		for(Returns item : reserveList) {
			
			if(item.getPartUnit().equals(reserve.getPartUnit())
					&& item.getWarehouse().equals(reserve.getWarehouse())
					&& item.getProject().equals(reserve.getProject())) {
				return item;
			}
			
		}
		
		return null;
	}


	public void discard(Long id) {
		
		Returns template = new Returns();
		template.setId(id);
		
		int idx = reserveList.indexOf(template);
		if(idx >= 0) {
			reserveList.remove(idx);
		}
		
	}
	
	public void clear() {
		reserveList.clear();
	}
	
	/**
	 * @return the empty
	 */
	public boolean isNotEmpty() {
		return !reserveList.isEmpty();
	}

	/**
	 * @return the reserveList
	 */
	public List<Returns> getReserveList() {
		return reserveList;
	}

	/**
	 * @return the mapReserved
	 */
	public Map<Long, Double> getMapReserved() {
		return mapReserved;
	}

}
